package com.example.myapplication.acticity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import com.example.myapplication.PlayService;
import com.example.myapplication.vo.MobileApplication;

public abstract class BaseActivity extends AppCompatActivity {

    public Context context;
   // public PlayService playService;
    private Boolean isboudn = false;//是否已经绑定


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
    }

    private ServiceConnection coon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            PlayService.PlayBinder playBinder = (PlayService.PlayBinder)iBinder;
            MobileApplication.getInstance().playService = playBinder.getPlayService();
            MobileApplication.getInstance().playService.setMusicUpdateListener(musicUpdateListener);
            //绑定成功之后调用监听的方法
            musicUpdateListener.onChange(MobileApplication.getInstance().playService.getCurrentPostion());
            musicUpdateListener.onPublish(MobileApplication.getInstance().playService.getCurrentProgress());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            MobileApplication.getInstance().playService = null;
            isboudn = false;
        }
    };
    //绑定服务
    public void binderPlayService(){
        if (!isboudn){

            Intent intent = new Intent(this,PlayService.class);
            bindService(intent,coon,BIND_AUTO_CREATE);
            isboudn = true;
        }
    }
    //解除绑定服务
    public void unbindPlaySerevce(){
        if (isboudn){
            unbindService(coon);
            isboudn = false;
        }
    }

    private PlayService.MusicUpdateListener musicUpdateListener = new PlayService.MusicUpdateListener() {
        @Override
        public void onPublish(int progress) {
            publish(progress);
        }

        @Override
        public void onChange(int position) {
            change(position);
        }
    };
    public abstract void  publish(int progress);
    public abstract void  change(int position);

    /**
     * 提示信息的方法
     * @param msg
     */
    public void showToast(String msg){
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    }

    /**
     * 跳转页面的方法
     * @param cls
     */
    public  void navigateTo(Class cls){
        startActivity(new Intent(context,cls));
    }
}

